package cn.tedu.v2;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 聊天室 Version1.1
 * 服务器 功能：1.服务器申请端口号：软件具备端口号
 *            2.在start方法中：等待客户端连接，返回 socket
 *                             IO读入
 *       【新增】3.所有服务器端异常，全部捕获，明确提示
 */
public class Server {
    private ServerSocket serverSocket;

    public Server() throws IOException {
        try {
            serverSocket = new ServerSocket(1019);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }


    public void start() {
        BufferedReader br = null;
        Socket socket = null;
        try {
            System.out.println("等待客户端连接");
            socket = serverSocket.accept();

            String ip = socket.getInetAddress().getHostAddress();
            System.out.println("客户端" + ip + "连接上了");

            InputStream is = socket.getInputStream();
            InputStreamReader isr =
                    new InputStreamReader(is, "UTF8");

            br = new BufferedReader(isr);

            while (true) {
                String str = br.readLine();
                System.out.println("客户端" + str);
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("请检查客户端/服务器端编码集：不一致~~");
        } catch (IOException e) {
            System.out.println("客户端连接失效了");
        } finally {
            //关闭socket
            if (br != null)
                try {
                    br.close();
                } catch (Exception e) {
                    System.out.println("读入流断开连接");
                }
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("客户端socket断开连接");
            }
        }

    }

    public static void main(String[] args) throws IOException {

        cn.tedu.v1.Server server = new cn.tedu.v1.Server();

        server.start();
    }

}